#include <stdio.h>  
#include <pthread.h>  
  
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;  
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;  
#define Max_size 5  
int buf[Max_size];  

int count = 0;
int index1 = 0;
  
void * write_test(void * arg) {
    pthread_mutex_lock(&lock);    
    while (1) {  
        
        if (index1 == Max_size) {  
            //唤醒
            pthread_cond_signal(&cond);
            pthread_cond_wait(&cond, &lock);  
        }       
        buf[index1++] = ++count;
        printf("write %d\n", count);
    }
    pthread_mutex_unlock(&lock);
}  
  
void * read_test(void * arg) { 
    pthread_mutex_lock(&lock); 
    while (1) {  
          
        if (index1 == 0) {  
            pthread_cond_signal(&cond);
            pthread_cond_wait(&cond, &lock);
        }  
        printf("read %d\n", buf[--index1]);
        
    }
    pthread_mutex_unlock(&lock);  
}  
  
int main(int argc, char const *argv[]) {  
    pthread_t write, read;  
    pthread_create(&write, NULL, write_test, NULL);  
    pthread_create(&read, NULL, read_test, NULL);  
    // 注意：这里没有退出机制，实际应用中需要实现  
    pthread_join(write, NULL);  
    pthread_join(read, NULL);  
    return 0;  
}